package io.objectOutStream;

import java.io.*;

public class objectOutStream {
    public static void main(String[] args) throws Exception {
        objectOutStream objectOutStream = new objectOutStream();
        objectOutStream.write();
        objectOutStream.read();
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //序列化
    public void write() throws IOException {
        String path = "d:/Test/create4.txt";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos);
        objectOutputStream.writeInt(1);//Integer
        objectOutputStream.writeBoolean(true);
        objectOutputStream.writeChar('a');
        objectOutputStream.writeUTF("avd");//String
        objectOutputStream.writeDouble(1.2);//double
        objectOutputStream.writeObject(new Dog("zs",23));
        objectOutputStream.close();
    }
    //反序列化
    public void read() throws Exception {
        String path = "d:/Test/create4.txt";

        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        int i = objectInputStream.readInt();
        boolean b = objectInputStream.readBoolean();
        //'''反序列化顺序要和序列化顺序一致
        char c = objectInputStream.readChar();
        String s = objectInputStream.readUTF();
        double v = objectInputStream.readDouble();
        Dog o = (Dog)objectInputStream.readObject();
        System.out.println(o.toString());
        objectInputStream.close();
        //o是dog 编译时时Object类型，运行时向下转型Dog类型，需要将Dog类的定义拷贝到可以引用的位置
    }
}

//不写时默认类型 访问权限只有同包能访问
class Dog implements Serializable {
    //序列化的版本，可以提高兼容性
    //static 和transient修饰的不会被序列化
    private static final long serialVersionUID = 1L;
    private String name;
    private Integer age;

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}